package com.smartkey.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.project.smartkey.R;
import com.smartkey.bean.AppInfo;
import com.smartkey.sharedpreferences.SharePreferencesUtil;
import com.smartkey.utils.AppUtil;
import com.smartkey.utils.ClickType;

public class AdapterAppPick extends BaseAdapter {

	List<AppInfo> defaultApps = new ArrayList<AppInfo>();
	private LayoutInflater inflater;
	private String selectedPakageName = null;

	public AdapterAppPick(Context context, ClickType clickType,
			boolean isDefault) {
		if (isDefault) {
			this.defaultApps = AppUtil.getDefaultAppListWithCheckStatus(
					context, clickType);
		} else {
			this.defaultApps = AppUtil.getNonSystemAppInfo(context);
		}
		inflater = LayoutInflater.from(context);
		SharePreferencesUtil preferencesUtil = new SharePreferencesUtil(context);
		switch (clickType) {
		case CLICK:
			selectedPakageName = preferencesUtil.getSingleClickValue();
			break;
		case DCLICK:
			selectedPakageName = preferencesUtil.getDoubleClickValue();
			break;
		case TCLICK:
			selectedPakageName = preferencesUtil.getTrifectaClickValue();
			break;
		}
	}

	@Override
	public int getCount() {
		return defaultApps.size();
	}

	@Override
	public Object getItem(int arg0) {
		return defaultApps.get(arg0);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		AppInfo appInfo = defaultApps.get(position);
		Holder holder;

		if (convertView == null) {
			convertView = inflater.inflate(R.layout.main_app_list_item, null);
			holder = getHolder(convertView);
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
		}
		holder.checkFlag.setVisibility(View.GONE);
		if (appInfo != null) {
			if (appInfo.appIcon != null) {
				holder.icon.setBackgroundDrawable(appInfo.appIcon);
			}
			if (appInfo.appName != null) {
				holder.name.setText(appInfo.appName);
			}
			if (appInfo.packageName != null
					&& appInfo.packageName.equals(selectedPakageName)) {
				holder.checkFlag.setVisibility(View.VISIBLE);
			}
		}

		return convertView;
	}

	private Holder getHolder(View convertView) {
		Holder holder = new Holder();
		holder.icon = (ImageView) convertView.findViewById(R.id.app_icon);
		holder.name = (TextView) convertView.findViewById(R.id.app_name);
		holder.checkFlag = (ImageView) convertView.findViewById(R.id.app_check);
		return holder;
	}

	private class Holder {
		ImageView icon;
		TextView name;
		ImageView checkFlag;
	}

}
